package doc2db.interfaces.mainWindow;

import doc2db.Keey;
import doc2db.Launcher;
import doc2db.UserProp;
import doc2db.fileWorker.FileBeginer;
import doc2db.fileWorker.FileIO;
import doc2db.interfaces.action.Doc2DbAction;
import doc2db.interfaces.action.Doc2DbDirAction;
import doc2db.interfaces.action.SendUserDbQuery;
import doc2db.interfaces.mainWindow.action.FileChousAction;
import doc2db.interfaces.mainWindow.action.MyMouseListener;
import doc2db.interfaces.xmledit.MTextArea;
import java.io.File;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.Font;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseListener;
import javax.swing.JPanel;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.LayoutStyle.ComponentPlacement;
import org.opu.gui.component.SplitPanelWithToogle;
import org.opu.stylepane.Ostermiller.Syntax.HighlightedDocument;

/**
 *  <p>Панель главного окна</p>
 * @author yuriy
 */
public final class MyPanel extends JPanel{
    /**нижняя панель*/
    public JPanel p = new JPanel();

    /**окно к котором привязанна панель*/
    private JFrame frame;
    /**фонты текстур*/
    private Font fon = UserProp.paneFont;
    /**слушатель мыши для кнопок скрытия*/
    private MouseListener rolloverButtonListener = new MyMouseListener();

    /**файлы с иконками*/
    private String picturePath [] =  {
        FileBeginer.resurse_resurseFolderPane+Keey.sp+"project_open.png",
        FileBeginer.resurse_resurseFolderPane+Keey.sp+"mark2.png",
        FileBeginer.resurse_resurseFolderPane+Keey.sp+"document-send.png",
        FileBeginer.resurse_resurseFolderPane+Keey.sp+"poinDown.png",
        FileBeginer.resurse_resurseFolderPane+Keey.sp+"poinRight.png",
        FileBeginer.resurse_resurseFolderPane+Keey.sp+"document-page-setup.png",
        FileBeginer.resurse_resurseFolderPane+Keey.sp+"loadDir.png"
    };

    // <editor-fold defaultstate="collapsed" desc="gui component at thi pane">
    /**поля для выбора файла для обработки*/
    public JButton fileChouse = new JButton();
    /**кнопка обработать файл*/
    public JButton submitFile = new JButton();
    /**кнопка обработать каталога с файлами*/
    public JButton submitDir = new JButton();
    /**кнопка обработать запрос в поле sqlToExe*/
    public JButton submitSql = new JButton();
    /** Поле ввода для ввода "Имя таблицы" */
    public JTextField fname = new JTextField(32);
    /** Поле ввода для ввода "Имя файла" */
    public JTextField file = new JTextField(32);
    /** Поле ввода для ввода SQL запросов */
    public MTextArea sqlToExe = new MTextArea(new HighlightedDocument());
    public JEditorPane textDBSelects = new MTextArea(HighlightedDocument.SQL_STYLE);
    public MyJEditorPane textWeekendInformation = new MyJEditorPane();
    public JTabbedPane textTemplete = new JTabbedPane();
    public JTextArea textTemp = new JTextArea();
    public JTextArea textMetaTemp = new JTextArea();
    public JScrollPane sp1 = new JScrollPane(textDBSelects);
    public JScrollPane sp2 = new JScrollPane(textWeekendInformation);
    public JPanel sp0 = new JPanel();
    public JScrollPane sp4;
    public JPanel pnlFileEntry = new JPanel();
    public JPanel pnlWeekInfo = new JPanel(new BorderLayout());//new GridLayout(1, 1));
    private SplitPanelWithToogle splitPanel = new SplitPanelWithToogle(pnlWeekInfo);
    // </editor-fold>

    /**
     *  Create new Instance of content pane of frame
     * @param f frame for wat it will be content pane
     * @param t Scroll pane with output
     */
    public MyPanel(JFrame f, JScrollPane t) {
        frame = f;
        sp4 = t;
        this.initVar();
        this.initComp();

        textTemp.setBackground(Color.WHITE);
        textMetaTemp.setBackground(Color.WHITE);
        textTemplete.setMinimumSize(new Dimension(200, 200));
        textTemplete.addTab("templetes", new JScrollPane(textTemp));
        textTemplete.addTab("metaTempletes", new JScrollPane(textMetaTemp));
        sp2.setPreferredSize(sp2.getMaximumSize());
        String s = FileBeginer.resurse_users_usersFolder + Keey.sp + UserProp.user + Keey.sp;
        textTemp.setText(FileIO.readFromFiles(s + FileBeginer.templatesName));
        textMetaTemp.setText(FileIO.readFromFiles(s + FileBeginer.metaTemplatesName));
        textTemp.setLineWrap(true);
        textMetaTemp.setLineWrap(true);

        setLayout(new BorderLayout());
        add(splitPanel, BorderLayout.CENTER);

        this.textDBSelectsSetVisible(UserProp.textDBSelects);
        this.textTempleteSetVisible(UserProp.textTemplete);
        this.textWeekendInformationSetVisible(UserProp.textWeekendInformation);
        this.textOutSetVisible(UserProp.textOut);
        this.textSqlSelectsSetVisible(UserProp.sqlSelectsArea);
        this.textPnlFileEntrySetVisible(UserProp.fileEntryField);
    }

    /**
     * <p>рзамещение компонентов на панели</p>
     * @deprecated 
     */
    public void addComponents(){
        //removeAll();
        //add(splitPanel, BorderLayout.CENTER);
    }

    /**
     * <p>инициализация компонентов и рзамещение их на панели</p>
     */
    private void initComp(){
        setLayout(new BorderLayout());
        boolean edit = false;
        
        textDBSelects.setEditable(edit);
        textWeekendInformation.setEditable(edit);
        textWeekendInformation.setBackground(Color.WHITE);
        textTemp.setEditable(edit);
        textMetaTemp.setEditable(edit);
        
        textDBSelects.setCursor(new Cursor(Cursor.TEXT_CURSOR));
        textWeekendInformation.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        textTemp.setCursor(new Cursor(Cursor.TEXT_CURSOR));
        textMetaTemp.setCursor(new Cursor(Cursor.TEXT_CURSOR));

        p.setVisible(edit);
        JProgressBar progressBar = new JProgressBar(0, 100);
        progressBar.setStringPainted(true);
        progressBar.setIndeterminate(true);
        progressBar.setPreferredSize(new Dimension(230, 20));
        progressBar.setMaximumSize(new Dimension(780, 20));
        p.add(progressBar);

        //this.addComponents();
    }

    /**
     * <p>иинициализация полней панели</p>
     */
    private void initVar(){
        this.initVarSize();
        this.initVarAction();

        sp0 = new JPanel();//new BorderLayout());
        JScrollPane sqlSp = new JScrollPane(sqlToExe);
        GroupLayout layout = new GroupLayout(sp0);

        sp0.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(sqlSp)
                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(submitSql)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(submitSql)
                .addContainerGap(259, Short.MAX_VALUE))
            .addComponent(sqlSp)
        );

        pnlWeekInfo.removeAll();
        pnlWeekInfo.add(sp2);
        int ps = GroupLayout.PREFERRED_SIZE;
        JLabel lblfname = this.getLabel("Имя таблицы");
        JLabel lblfile = this.getLabel("Имя файла");
        GroupLayout mainPanelLayout = new GroupLayout(pnlFileEntry);

        pnlFileEntry.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(lblfname)
                        .addPreferredGap(ComponentPlacement.RELATED)
                        .addComponent(fname, ps, GroupLayout.DEFAULT_SIZE, ps))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(lblfile)
                        .addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(file, ps, GroupLayout.DEFAULT_SIZE, ps)))
                .addPreferredGap(ComponentPlacement.RELATED)
                .addComponent(fileChouse, ps, GroupLayout.DEFAULT_SIZE, ps)
                .addPreferredGap(ComponentPlacement.RELATED)
                .addComponent(submitDir, ps, GroupLayout.DEFAULT_SIZE, ps)
                .addPreferredGap(ComponentPlacement.RELATED)
                .addComponent(submitFile, ps, GroupLayout.DEFAULT_SIZE, ps)
                .addContainerGap(38, Short.MAX_VALUE)
                )
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(lblfname)
                    .addComponent(fname, ps, GroupLayout.DEFAULT_SIZE, ps))
                .addPreferredGap(ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(lblfile)
                    .addComponent(file, ps, GroupLayout.DEFAULT_SIZE, ps)
                    .addComponent(fileChouse, ps, GroupLayout.DEFAULT_SIZE, ps)
                    .addComponent(submitDir, ps, GroupLayout.DEFAULT_SIZE, ps)
                    .addComponent(submitFile, ps, GroupLayout.DEFAULT_SIZE, ps))
                )
        );
    }

    /**
     * прикрепление к полям панели соответствующие действие
     */
    private void initVarAction(){
        submitSql.addActionListener(new SendUserDbQuery(textWeekendInformation,
                textDBSelects, sqlToExe));
        submitFile.addActionListener(new Doc2DbAction((MyFrame)frame, 
                file, fname, textDBSelects, textWeekendInformation));
        submitDir.addActionListener(new Doc2DbDirAction((MyFrame)frame,
                file, fname, textDBSelects, textWeekendInformation));

        final FileChousAction fca = new FileChousAction(null);
        fileChouse.addActionListener(fca);
        file.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (! Keey.debug) {
                    fca.actionPerformed(null);
                }
            }
        });
        file.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (! Keey.debug) {
                    file.setText("");
                    fca.actionPerformed(null);
                }
            }
        });

        textWeekendInformation.addHyperlinkListener(new MyHyperlinkListener(
                textDBSelects, textWeekendInformation));
        textWeekendInformation.setRoot(sp2);
        textWeekendInformation.setRootPnl(pnlWeekInfo);

        final JEditPContentMenu m = new JEditPContentMenu(textWeekendInformation, textDBSelects);
        textWeekendInformation.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                if(e.isPopupTrigger()){
                    if (textWeekendInformation.isOnHyperLink) {
                        if (!textWeekendInformation.isInTable) {
                            m.hyperLinkName = "" + textWeekendInformation.HyperLinkName;
                            m.getLynkMenu().show(e.getComponent(), e.getX(), e.getY());
                        }else{
                            m.hyperLinkName = "" + textWeekendInformation.HyperLinkName;

                        }
                    } else {
                        if(e.isPopupTrigger())
                            m.getLynkSelectPaneMenu(textWeekendInformation).show(e.getComponent(),
                                e.getX(), e.getY());
                    }
                }
            }
        });
    }

    /**
     * <p>определение размера и параметров компонентов
     * панели</p>
     */
    private void initVarSize(){
        this.initVarSizeFont();
        this.initVarSizeButon(new Dimension(34, 34), new Dimension(180, 12), new Dimension(180, 40));
        this.initVarSizeToolTipText();
        this.initVarSizeIcon();
        this.initVarSizeRolloverButton();

        fname.setForeground(Color.BLUE);
        sqlToExe.setBackground(Color.WHITE);
        HighlightedDocument doc = (HighlightedDocument) sqlToExe.getDocument();
        doc.setHighlightStyle(HighlightedDocument.SQL_STYLE);
        sqlToExe.setAutoscrolls(true);
        
    }

    /**
     *  <p>прикрепляет действия к кнопкам когда на
     * них наводится курсор мыши</p>
     */
    private void initVarSizeRolloverButton(){
        boolean content = false;
        fileChouse.setContentAreaFilled(content);
        fileChouse.addMouseListener(rolloverButtonListener);
        submitFile.setContentAreaFilled(content);
        submitFile.addMouseListener(rolloverButtonListener);
        submitDir.setContentAreaFilled(content);
        submitDir.addMouseListener(rolloverButtonListener);
        submitSql.setContentAreaFilled(content);
        submitSql.addMouseListener(rolloverButtonListener);
    }

    /**
     * <p>Определяет фонт элементов панели</p>
     */
    private void initVarSizeFont(){
        fileChouse.setFont(fon);
        submitFile.setFont(fon);
        submitDir.setFont(fon);
        submitSql.setFont(fon);
        fname.setFont(fon);
        file.setFont(fon);
        sqlToExe.setFont(UserProp.textFont);
        textDBSelects.setFont(UserProp.textFont);
        textWeekendInformation.setFont(UserProp.textFont);
        textTemplete.setFont(UserProp.textFont);
        textTemp.setFont(UserProp.textFont);
        textMetaTemp.setFont(UserProp.textFont);
    }

    /**
     *  <p>Определяет изначальный и максимальный размер
     * элементов панели</p>
     * @param butn размер кнопок
     * @param spl размер текстовых полей
     * @param sql размер метки заголовка для <i>sql</i> запроса
     */
    private void initVarSizeButon(Dimension butn, Dimension spl, Dimension sql){
        fileChouse.setPreferredSize(butn);
        submitFile.setPreferredSize(butn);
        submitDir.setPreferredSize(butn);
        submitSql.setPreferredSize(butn);

        textDBSelects.setPreferredSize(spl);
        textWeekendInformation.setPreferredSize(spl);
        textTemplete.setPreferredSize(spl);

        fileChouse.setMaximumSize(butn);
        submitFile.setMaximumSize(butn);
        submitDir.setMaximumSize(butn);
        submitSql.setMaximumSize(butn);

        file.setMaximumSize(file.getPreferredSize());
        fname.setMaximumSize(fname.getPreferredSize());

        sp0.setPreferredSize(sql);
    }

    /**
     * <p>Прекрепляет контекстные подсказки к каждому
     * компоненту панели</p>
     */
    private void initVarSizeToolTipText(){
        fileChouse.setToolTipText("выбор файла для обработки");
        submitFile.setToolTipText("выполнить обработку файла");
        submitDir.setToolTipText("выполнить обработку каталога");
        submitSql.setToolTipText ("выполнить sql запрос");
    }

    /**
     * <p>определяет соответствующие иконки для соответсятвующих
     * компонентов</p>
     */
    private void initVarSizeIcon(){
        fileChouse.setIcon(new ImageIcon(picturePath[0]));
        submitFile.setIcon(new ImageIcon(picturePath[1]));
        submitDir.setIcon(new ImageIcon(picturePath[6]));
        submitSql.setIcon(new ImageIcon(picturePath[2]));

        String path = "pane/";
        if (!new File(picturePath[0]).exists()) {
            fileChouse.setIcon(Launcher.getIcon(path + "project_open.png"));
        }
        if (!new File(picturePath[1]).exists()) {
            submitFile.setIcon(Launcher.getIcon(path + "mark2.png"));
        }
        if (!new File(picturePath[6]).exists()) {
            submitDir.setIcon(Launcher.getIcon(path + "loadDir.png"));
        }
        if (!new File(picturePath[2]).exists()) {
            submitSql.setIcon(Launcher.getIcon(path + "document-send.png"));
        }
    }

    public void textDBSelectsSetVisible(boolean b){
        //textDBSelects.setVisible(false);
        sp1.setVisible(false);
        String name = "Запросы к БД";
        if (b){
            splitPanel.addTab(name, null, sp1);
        } else {
            splitPanel.remove(name);
        }
    }

    public void textTempleteSetVisible(boolean b){
        textTemplete.setVisible(false);
        String name = "Шаблон";
        if (b){
            splitPanel.addTab(name, null, textTemplete);
        } else {
            splitPanel.remove(name);
        }
    }

    public void textWeekendInformationSetVisible(boolean b){
        textWeekendInformation.setVisible(b);
        pnlWeekInfo.setVisible(b);
        sp2.setVisible(b);
    }

    public void textOutSetVisible(boolean b){
        sp4.setVisible(b);
        String name = "Вывод";
        if (b){
            splitPanel.addTab(name, null, sp4);
        } else {
            splitPanel.remove(name);
        }
    }

    public void textSqlSelectsSetVisible(boolean b){
        sp0.setVisible(b);
        String name = "Ввод Sql";
        if (b){
            splitPanel.addTab(name, null, sp0);
        } else {
            splitPanel.remove(name);
        }
    }

    public void textPnlFileEntrySetVisible(boolean b){
        pnlFileEntry.setVisible(b);
        Keey.tableName = b;
        String name = "Ввод файла";
        if (b){
            splitPanel.addTab(name, null, pnlFileEntry);
        } else {
            splitPanel.remove(name);
        }
    }

    private JLabel getLabel(String text){
        JLabel lbl = new JLabel(text);
        lbl.setFont(UserProp.paneFont);
        return lbl;
    }
}
